package camera;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Socket;

import se.lth.cs.realtime.JThread;
import camerainterfaces.Axis211AInterface;

/**
 * The class CameraServer is a server that receives messages through a TCP/IP
 * socket and sends pictures through a UPD/IP socket to the client. The class
 * uses a connected Axis camera either a fake, proxy or the real camera.
 */
public class CameraServer extends JThread {
	private Axis211AInterface camera;
	private BufferedReader input;
	private DatagramSocket sendSocket;
	private Socket listenSocket;
	private boolean running;

	/**
	 * Initiates the class and starts the input.
	 * 
	 * @param listenSocket
	 *            - the socket which the server receives messages through
	 * @param sendSocket
	 *            - the UDP/IP socket which is used for sending pictures
	 * @param cam
	 *            - the connected camera.
	 */
	public CameraServer(Socket listenSocket, DatagramSocket sendSocket,
			Axis211AInterface cam) {
		this.camera = cam;
		this.sendSocket = sendSocket;
		this.listenSocket = listenSocket;
		running = true;
		try {
			input = new BufferedReader(new InputStreamReader(listenSocket
					.getInputStream()));
		} catch (IOException e) {
			System.err
					.println("An I/O Exception Occured in Cameraserver while setting up input/outputs");
		}
	}

	/**
	 * Run when the thread is started. Checks the message received and calls the
	 * method sendPicture which send the picture to the Client.
	 */
	@Override
	public void run() {
		String s = "";
		while (running) {
			try {
				s = input.readLine();
			} catch (IOException e) {
				System.err
						.println("An I/O Exception Occured in Cameraserver while receiving information, shutting down");
				running = false;
			}
			if (s == null) {// end of stream reached
				running = false;
				break;
			}
			if (s.equals("GIEF")) {
				sendPicture();
			} else {
				break;
			}
		}
	}

	/**
	 * Helper that sends pictes over udp.
	 */
	private void sendPicture() {
		byte array[] = new byte[camera.getImageBufferSize()];
		int len = camera.getJPEG(array, 0);
		DatagramPacket packet = new DatagramPacket(array, len, listenSocket
				.getInetAddress(), 8000);
		try {
			sendSocket.send(packet);
		} catch (IOException e) {
			System.err
					.println("An I/O Exception Occured in Cameraserver while transmitting a picture, shutting down");
			running = false;
		}

	}

}
